#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// LiteOS内核头文件
#include "los_task.h"
#include "ohos_init.h"
// 外设驱动头文件
#include "picture.h"
#include "lcd.h"
#include "iot_errno.h"
#include "iot_gpio.h"
#include "los_event.h"
#include "iot_uart.h"
#include "los_queue.h"  
#include "los_mux.h"  // 互斥锁支持
#include "iot_pwm.h"
#include "iot_adc.h"  // 添加ADC支持Cold
#include "sht30.h"
#include "bh1750.h"
#define SERVICE_ID "qs"  // 云平台服务ID
// 串口配置
#define UART_ID         EUART0_M0        // 串口号
#define STRING_MAXSIZE  256              // 字符串最大长度
#define UART_QUEUE_SIZE 8                // 消息队列容量
#define UART_MSG_SIZE   159              // 单条消息最大长度
#define JSON_BUFFER_SIZE 400             // JSON数据缓冲区大小
static unsigned char buffer[UART_MSG_SIZE];  // 串口接收缓冲区
// 在文件顶部定义
#define MAX_JSON_LEN 320
#define MAX_CONTENT_LEN 100
//引脚定义
#define GPIO_Hot      GPIO0_PB1 //继电器引脚热
#define GPIO_Cold     GPIO0_PB0//继电器引脚冷
#define GPIO_Fun      GPIO0_PA5 //继电器风扇引脚
#define GPIO_BODY_INDUCTION GPIO0_PA3//人体传感器引脚
//RGBpwm通道H
#define LED_R_PORT EPWMDEV_PWM1_M1
#define LED_G_PORT EPWMDEV_PWM7_M1
#define LED_B_PORT EPWMDEV_PWM0_M1
#define SG90_PWM   EPWMDEV_PWM6_M0 // SG90舵机PWM
//按键通道
#define KEY_ADC_CHANNEL 7  
//变量声明
static float tem_w = 0.0;//温度
static float humi_s = 0.0;//湿度
static double Light = 0.0;//光照
static unsigned int duty_min = 1;
static unsigned int duty_max = 99;
//互斥锁变量（设备标志位）
static unsigned int  Led_Status = 0;//灯光
static unsigned int  Fan_Status = 0;//风扇
static unsigned int  air_cold = 0;//制冷
static unsigned int  air_hot = 0;//制热
static unsigned int MODE = 0;//0为手动1为自动
static bool g_lastBodyState = false;
// 互斥锁定义
static unsigned int g_uartMutex;    // 保护串口缓冲区
static unsigned int g_LedMutex;   	// 保护灯光状态
static unsigned int g_FanMutex;  	// 保护风扇状态
static unsigned int g_coldMutex;  	// 保护制冷状态
static unsigned int g_hotMutex; 	// 保护制热状态
static unsigned int g_modeMutex;    // 保护模式状态
//自动化控制标志位
static unsigned int temphigh_flag = 35;//高温标志位
static unsigned int templow_flag = 35;//低温标志位
static unsigned int light_flag = 100;//光照标志位
// 辅助函数：安全更新灯光状态
void update_Led_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_LedMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    
    Led_Status = new_status;
    if (new_status==1) {
		// 白色灯光
		IoTPwmStart(LED_R_PORT, duty_max, 1000);  // 100%占空比
		IoTPwmStart(LED_G_PORT, duty_max, 1000);  // 100%占空比
		IoTPwmStart(LED_B_PORT, duty_max, 1000);  // 100%占空比
		printf("灯光开启\n");
	} else { // 所有灯灭
		IoTPwmStart(LED_R_PORT, duty_min, 1000);
		IoTPwmStart(LED_G_PORT, duty_min, 1000);
		IoTPwmStart(LED_B_PORT, duty_min, 1000);
		printf("灯光关闭\n");
	}

    LOS_MuxPost(g_LedMutex);
    
    // 更新LCD消息
   /* snprintf(g_lcd_message, sizeof(g_lcd_message), 
             "灯光已%s", new_status ? "开启" : "关闭");*/
}

// 辅助函数：安全获取LED状态
unsigned int get_Led_status()
{
    unsigned int status;
    
    if (LOS_MuxPend(g_LedMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; 
    }
    
    status = Led_Status;
    
    LOS_MuxPost(g_LedMutex);
    return status;
}
// 辅助函数：安全更新风扇状态
void update_Fan_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_FanMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    
    Fan_Status = new_status;
    
    // 控制风扇输出引脚
	
    IotGpioValue outputValue = new_status ? IOT_GPIO_VALUE1 : IOT_GPIO_VALUE0;
    IoTGpioSetOutputVal(GPIO_Fun, outputValue);

    LOS_MuxPost(g_FanMutex);
    
    // 更新LCD消息
   /* snprintf(g_lcd_message, sizeof(g_lcd_message), 
             "灯光已%s", new_status ? "开启" : "关闭");*/
}

// 辅助函数：安全获取风扇状态
unsigned int get_Fan_status()
{
    unsigned int status;
    
    if (LOS_MuxPend(g_FanMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; 
    }
    
    status = Fan_Status;
    
    LOS_MuxPost(g_FanMutex);
    return status;
}
// 辅助函数：安全更新制冷状态
void update_Cold_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_coldMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    
    air_cold = new_status;
    
    // 控制制冷输出引脚
	
    IotGpioValue outputValue = new_status ? IOT_GPIO_VALUE1 : IOT_GPIO_VALUE0;
    IoTGpioSetOutputVal(GPIO_Cold, outputValue);
    
    LOS_MuxPost(g_coldMutex);
    
    // 更新LCD消息
   /* snprintf(g_lcd_message, sizeof(g_lcd_message), 
             "灯光已%s", new_status ? "开启" : "关闭");*/
}

// 辅助函数：安全获取制冷状态
unsigned int get_Cold_status()
{
    unsigned int status;
    
    if (LOS_MuxPend(g_coldMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; 
    }
    
    status = air_cold;
    
    LOS_MuxPost(g_coldMutex);
    return status;
}
// 辅助函数：安全更新制热状态
void update_Hot_status(unsigned int new_status)
{
    if (LOS_MuxPend(g_hotMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;
    }
    
    air_hot = new_status;
    
    // 控制制热输出引脚
	
    IotGpioValue outputValue = new_status ? IOT_GPIO_VALUE1 : IOT_GPIO_VALUE0;
    IoTGpioSetOutputVal(GPIO_Hot, outputValue);
    
    LOS_MuxPost(g_hotMutex);
    
    // 更新LCD消息
   /* snprintf(g_lcd_message, sizeof(g_lcd_message), 
             "灯光已%s", new_status ? "开启" : "关闭");*/
}

// 辅助函数：安全获取制热状态
unsigned int get_Hot_status()
{
    unsigned int status;
    
    if (LOS_MuxPend(g_hotMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0; 
    }
    
    status = air_hot;
    
    LOS_MuxPost(g_hotMutex);
    return status;
}
// 辅助函数：安全更新模式状态
void update_Mode_status(unsigned int new_status)
{
    // 获取互斥锁（永久等待直到获取成功）
    if (LOS_MuxPend(g_modeMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return;  // 获取锁失败则直接返回
    }
    
    // 更新全局模式变量（只允许0或1）
    MODE =  new_status ? 1 : 0;  // 确保值只能是0或1
    
    // 释放互斥锁
    LOS_MuxPost(g_modeMutex);
    
    // 可选：更新LCD显示
    /* snprintf(g_lcd_message, sizeof(g_lcd_message), 
             "工作模式：%s", MODE ? "自动" : "手动"); */
}

// 辅助函数：安全获取模式状态
unsigned int get_Mode_status()
{
    unsigned int status;
    
    // 获取互斥锁
    if (LOS_MuxPend(g_modeMutex, LOS_WAIT_FOREVER) != LOS_OK) {
        return 0;  // 获取失败返回默认值
    }
    
    // 读取当前模式状态
    status = MODE;
    
    // 释放互斥锁
    LOS_MuxPost(g_modeMutex);
    
    return status;
}
//GPIO初始化
void GPIO_init()
{
    IoTGpioInit(GPIO_Hot);
    IoTGpioInit(GPIO_Cold);
    IoTGpioInit(GPIO_Fun);

    IoTGpioSetDir(GPIO_Hot, IOT_GPIO_DIR_OUT);
     IoTGpioSetOutputVal(GPIO_Hot, IOT_GPIO_VALUE0);
    IoTGpioSetDir(GPIO_Cold, IOT_GPIO_DIR_OUT);
     IoTGpioSetOutputVal(GPIO_Cold, IOT_GPIO_VALUE0);
    IoTGpioSetDir(GPIO_Fun, IOT_GPIO_DIR_OUT);
     IoTGpioSetOutputVal(GPIO_Fun, IOT_GPIO_VALUE0);
}
/***************************************************************
* 函数名称: adc_dev_init
* 说    明: 初始化ADC
* 参    数: 无
* 返 回 值: 0为成功，反之为失败
***************************************************************/
static unsigned int adc_dev_init()
{
    unsigned int ret = 0;

    /* 初始化ADC */
    ret = IoTAdcInit(KEY_ADC_CHANNEL);

    if(ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: ADC Init fail\n", __FILE__, __func__, __LINE__);
    }

    return ret;
}

/***************************************************************
* 函数名称: adc_get_voltage
* 说    明: 获取ADC电压值
* 参    数: 无
* 返 回 值: 电压值
***************************************************************/
static float adc_get_voltage()
{
    unsigned int ret = IOT_SUCCESS;
    unsigned int data = 0;

    /* 获取ADC值 */
    ret = IoTAdcGetVal(KEY_ADC_CHANNEL, &data);

    if (ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: ADC Read Fail\n", __FILE__, __func__, __LINE__);
        return 0.0;
    }

    return (float)(data * 3.3 / 1024.0);
}
//获取人体器数据
void body_induction_get_state(bool *dat)
{
    IotGpioValue value = IOT_GPIO_VALUE0;

    IoTGpioGetInputVal(GPIO_BODY_INDUCTION, &value);

    if (value) 
    {
        *dat = true;
    }
    else
    {
        *dat = false;
    }
}

void rgb_init(void)
{
    unsigned int ret;
   
    int blinkState = 0;  // 闪烁状态：0-灭，1-亮
     /* 初始化PWM */
    ret = IoTPwmInit(LED_R_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", LED_R_PORT);
    }

    ret = IoTPwmInit(LED_G_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", LED_G_PORT);
    }

    ret = IoTPwmInit(LED_B_PORT);
    if (ret != 0) {
        printf("IoTPwmInit failed(%d)\n", LED_B_PORT);
    }
        printf("RGB LED任务启动...\n");
    
}
//设备初始化
void Equipment_init()
{
    update_Led_status(0);
    update_Hot_status(0);
    update_Cold_status(0);
    update_Fan_status(0);
}
//人体传感器初始化
void body_induction_dev_init(void)
{
    IoTGpioInit(GPIO_BODY_INDUCTION);
    IoTGpioSetDir(GPIO_BODY_INDUCTION, IOT_GPIO_DIR_IN);
}
void Lock_Thread(void)
{
  unsigned int ret;
  unsigned char LockStatus = 0;
  ret = IoTPwmInit(SG90_PWM);
  if(ret != LOS_OK)
  {
    printf("舵机初始化失败");
  }
  while(1)
  {
    LockStatus = Get_Lock_Status();
    if(LockStatus == 1)
    {
      IoTPwmStart(SG90_PWM,3,50);
    }
    else
    {
      IoTPwmStart(SG90_PWM,8,50);
    }
    LOS_Msleep(500);
  }
  }
//环境数据采集采集任务
void EDA_task(void)
{

    double sht30_data[2] = {0};
    
    sht30_init();  // 初始化传感器
    bh1750_init();
    GPIO_init();//初始化GPIO
    rgb_init();//初始化rgb
    while (1)
     {
        sht30_read_data(sht30_data);  // 读取数据
       bh1750_read_data(&Light);
        // 更新全局变量
        tem_w = sht30_data[0];
        humi_s = sht30_data[1];  
               
        LOS_Msleep(1000);  //一秒采集一次
    }
}
//自动化任务
void automatic_control_task() {   
    Equipment_init();
    
    // 初始化上一次的状态记录变量
    int last_led_status = -1;     // 初始化为无效值，确保第一次会更新
    int last_hot_status = -1;
    int last_cold_status = -1;
    int last_fan_status = -1;
    
    while (1) {
        if (MODE == 1) {  // 仅在自动模式下运行
            // 计算当前应有的状态
            int current_led_status = (Light < light_flag) ? 1 : 0;
            int current_hot_status = (tem_w < templow_flag) ? 1 : 0;
            int current_cold_status = (tem_w > temphigh_flag) ? 1 : 0;
            int current_fan_status = ((tem_w < temphigh_flag) && (tem_w > templow_flag)) ? 1 : 0;
            
            // 检查状态是否变化，只在变化时更新
            if (current_led_status != last_led_status) {
                update_Led_status(current_led_status);
                last_led_status = current_led_status;
            }
            
            if (current_hot_status != last_hot_status) {
                update_Hot_status(current_hot_status);
                last_hot_status = current_hot_status;
            }
            
            if (current_cold_status != last_cold_status) {
                update_Cold_status(current_cold_status);
                last_cold_status = current_cold_status;
            }
            
            if (current_fan_status != last_fan_status) {
                update_Fan_status(current_fan_status);
                last_fan_status = current_fan_status;
            }
        }
        
        LOS_Msleep(100); // 缩短检查间隔为100ms，响应更及时但负载仍低
    }
}
//感应门任务


void Lock_Thread(void)
{
    unsigned int ret;
    bool currentState = false;
    
    // 初始化舵机PWM
    ret = IoTPwmInit(SG90_PWM);
    if(ret != LOS_OK) {
        printf("舵机初始化失败");
        return;
    }
    
    // 初始状态关门
    IoTPwmStart(SG90_PWM, 8, 50);
    
    while(1) {
        // 获取当前人体感应状态
        body_induction_get_state(&currentState);
        
        // 状态变化检测
        if(currentState != g_lastBodyState) {
            if(currentState) {
                // 检测到有人：开门
                IoTPwmStart(SG90_PWM, 3, 50);
                printf("有人靠近，开门\n");
            } else {
                // 无人：关门
                IoTPwmStart(SG90_PWM, 8, 50);
                printf("无人，关门\n");
            }
            
            // 更新状态记录
            g_lastBodyState = currentState;
        }
        
        LOS_Msleep(200);  // 降低检测频率
    }
}
//一键断电任务
void Off_task()
{    
    update_Mode_status(0);
    Equipment_init();
}
/***************************************************************
* 函数名称: report_sensors_to_cloud
* 功能说明: 上报传感器数据到云平台（优化版）
* 优化点:
*   1. 单次上报所有数据，减少AT指令数量
*   2. 添加缓冲区溢出保护
*   3. 增加错误处理
*   4. 减少延时等待时间
***************************************************************/
void report_sensors_to_cloud()
{
    
    char pubtemp[256];
    char pubhumidity[256];
    char publight[256];

    char publed[256];
    char pubfun[256];
    char pubcold[256];
    char pubhot[256];
    char pubmode[256];


    sprintf(pubtemp,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"temp\\\":%.2f}}]}\",0,0\r\n",tem_w);
    IoTUartWrite(UART_ID, pubtemp, strlen(pubtemp));
    printf("串口发送: %s\n", pubtemp);
     LOS_Msleep(150);
    sprintf(pubhumidity,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"humi\\\":%.2f}}]}\",0,0\r\n",humi_s);
    IoTUartWrite(UART_ID, pubhumidity, strlen(pubhumidity));
    printf("串口发送: %s\n", pubhumidity);
     LOS_Msleep(150);
    sprintf(publight,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"light\\\":%4d}}]}\",0,0\r\n",(int)Light);     
    IoTUartWrite(UART_ID, publight, strlen(publight));
    printf("串口发送: %s\n", publight);
     LOS_Msleep(150);
    sprintf(publed,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"lamplight_flag\\\":%d}}]}\",0,0\r\n",get_Led_status());
    IoTUartWrite(UART_ID, publed, strlen(publed));
    printf("串口发送: %s\n", publed);
     LOS_Msleep(150);
    sprintf(pubfun,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"fan_flag\\\":%d}}]}\",0,0\r\n",get_Fan_status());
    IoTUartWrite(UART_ID, pubfun, strlen(pubfun));
    printf("串口发送: %s\n", pubfun);
     LOS_Msleep(150);
    sprintf(pubcold,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"airconditioner_flag\\\":%d}}]}\",0,0\r\n",get_Cold_status());    
    IoTUartWrite(UART_ID, pubcold, strlen(pubcold));
    printf("串口发送: %s\n", pubcold);
     LOS_Msleep(150);
    sprintf(pubhot,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"heating_flag\\\":%d}}]}\",0,0\r\n",get_Hot_status());
    IoTUartWrite(UART_ID, pubhot, strlen(pubhot));
    printf("串口发送: %s\n", pubhot);
     LOS_Msleep(150);
    sprintf(pubhot,"AT+MQTTPUB=0,\"$oc/devices/686a8d6ba72147363d8e5b24_0001/sys/properties/report\",\"{\\\"services\\\":[{\\\"service_id\\\":\\\"qs\\\"\\,\\\"properties\\\":{\\\"mode_flag\\\":%d}}]}\",0,0\r\n",get_Mode_status());
    IoTUartWrite(UART_ID, pubmode, strlen(pubmode));
    printf("串口发送: %s\n", pubmode);
     LOS_Msleep(150); 
     
/*
    char json_buffer[JSON_BUFFER_SIZE];  // JSON缓冲区
    
    // 构建JSON字符串（添加温湿度数据）
    int len = snprintf(json_buffer, sizeof(json_buffer),
    "{\"services\":[{"
    "\"service_id\":\"%s\","    // 服务ID
    "\"properties\":{"          // 属性列表
    "\"Temperature\":%.1f,"     // 新增温度值（保留1位小数）
    "\"Humidity\":%.1f,"        // 新增湿度值（保留1位小数）
    "\"light\":%4d,"            //光照
    "\"lamplight_flag\":%d,"        // 灯光设备状态
    "\"fan_flag\":%d,"              // 风扇设备状态
    "\"airconditioner_flag\":%d,"   // 空调设备状态
    "\"heating_flag\":%d,"          // 制暖设备状态
    "}}]}",  // JSON结束
    SERVICE_ID,
    tem_w,     
    humi_s,        
    (int)Light,
    get_Led_status(),
    get_Fan_status(),
    get_Cold_status(),
    get_Hot_status());  // 当前定位方式文本
    
    // 检查JSON构建是否成功
    if (len > 0 && len < sizeof(json_buffer)) {
        IoTUartWrite(UART_ID, (unsigned char*)json_buffer, len);
        printf("[MQTT] Sending data: %s\n", json_buffer);
        printf("[周期上报] 传感器数据已上报\n");
    } else {
        printf("JSON数据构造失败! 长度:%d\n", len);
    }
        */
}
//串口发送
void uart_send_task(void)
{   
     // MQTT连接指令序列
    unsigned char str0[] = "ATE0\r\n";
    unsigned char str1[] = "AT\r\n";
    unsigned char str2[] = "AT+CWMODE=1\r\n";
    unsigned char str3[] = "AT+CWDHCP=1,1\r\n";
    unsigned char str4[] = "AT+RST\r\n";
    unsigned char str5[] = "AT+CWJAP=\"MY\",\"12345678\"\r\n";
    unsigned char str6[] = "AT+MQTTUSERCFG=0,1,\"NULL\",\"686a8d6ba72147363d8e5b24_0001\",\"d3361552aaf785e39748e01f8fb990264f020c052fc2dcdbb23709b45b65e929\",0,0,\"\"\r\n";
    unsigned char str7[] = "AT+MQTTCLIENTID=0,\"686a8d6ba72147363d8e5b24_0001_0_0_2025070707\"\r\n";
    unsigned char str8[] = "AT+MQTTCONN=0,\"258b41b5d3.st1.iotda-device.cn-south-1.myhuaweicloud.com\",1883,1\r\n";
    unsigned char topic[] = "AT+MQTTSUB=0,\"t\",1\r\n";
    
    // 串口配置参数
    IotUartAttribute attr = {
        .baudRate = 115200,                  // 波特率115200
        .dataBits = IOT_UART_DATA_BIT_8,     // 8位数据位
        .pad = IOT_FLOW_CTRL_NONE,           // 无流控
        .parity = IOT_UART_PARITY_NONE,      // 无校验
        .rxBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK,  // 非阻塞接收
        .stopBits = IOT_UART_STOP_BIT_1,     // 1位停止位
        .txBlock = IOT_UART_BLOCK_STATE_NONE_BLOCK   // 非阻塞发送
    };
    
    // 初始化串口
    if (IoTUartInit(UART_ID, &attr) != IOT_SUCCESS) {
        printf("串口初始化失败!\n");
        return;
    }
    printf("串口初始化成功！\n");
    /****************************************************
    * 第一阶段：通信模块初始化
    ****************************************************/
    printf("\n===== 4G通信模块初始化 =====\n");
    // 建立4G连接
    IoTUartWrite(UART_ID, str1, strlen(str1));
    printf("串口发送: %s\n", str1);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str0, strlen(str0));
    printf("串口发送: %s\n", str0);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str2, strlen(str2));
    printf("串口发送: %s\n", str2);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str3, strlen(str3));
    printf("串口发送: %s\n", str3);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str4, strlen(str4));
    printf("串口发送: %s\n", str4);
    LOS_Msleep(500);
    IoTUartWrite(UART_ID, str5, strlen(str5));
    printf("串口发送: %s\n", str5);
    LOS_Msleep(2000);
    IoTUartWrite(UART_ID, str6, strlen(str6));
    printf("串口发送: %s\n", str6);
    LOS_Msleep(2000);
    IoTUartWrite(UART_ID, str7, strlen(str7));
    printf("串口发送: %s\n", str7);
    LOS_Msleep(2000);
    IoTUartWrite(UART_ID, str8, strlen(str8));
    printf("串口发送: %s\n", str8);
    LOS_Msleep(2000);
    IoTUartWrite(UART_ID, topic, strlen(topic));
    printf("串口发送: %s\n", topic);
    LOS_Msleep(1500);
    printf("MQTT连接成功！\n");

    LOS_Msleep(200);
    printf("通信模块初始化完成!\n");

    /****************************************************
    * 第二阶段：主循环任务
    ****************************************************/
    // 传感器上报计时器
    unsigned int secondsCounter = 0;       // 秒计数器
    const unsigned int REPORT_INTERVAL = 2; // 3秒上报周期
    while (1)
    {
        /******************************************
        * 周期性数据上报
        ******************************************/
       
        secondsCounter++;
        if (secondsCounter >= REPORT_INTERVAL) {  // 达到上报周期
            printf("温度: %.2f 湿度：%.2f 光照：%.2f\n", tem_w,humi_s,Light);
            report_sensors_to_cloud();  // 周期性上报
            secondsCounter = 0;          // 重置计数器
        }

        LOS_Msleep(1000); // 1秒循环一次
    }

}
/***************************************************************
* 函数名称: uart_recv_task
* 功能说明: 串口数据接收任务
* 主要功能:
*   1. 接收串口数据
***************************************************************/
void uart_recv_task(void)
{
    int len;

    printf("串口接收任务启动...\n");
    while (1) {
        unsigned char temp_buffer[UART_MSG_SIZE] = {0};  // 临时缓冲区
        
        // 非阻塞读取串口数据
        len = IoTUartRead(UART_ID, temp_buffer, UART_MSG_SIZE - 1);
        
        if (len > 0) {
            // 申请串口缓冲区锁
            if (LOS_MuxPend(g_uartMutex, LOS_WAIT_FOREVER) != LOS_OK) {
                printf("获取串口缓冲区锁失败!\n");
                continue;
            } else {
                // 复制数据到全局缓冲区
                memcpy(buffer, temp_buffer, len);
                buffer[len] = '\0';  // 确保字符串结束
                LOS_Msleep(50);
                // 释放互斥锁
                LOS_MuxPost(g_uartMutex);

                // 打印可读内容（ASCII格式）
                printf("串口接收到:%s\n", temp_buffer);
                // ===== 新增：云平台控制命令解析 =====
                
                char *cloudMsg = strstr((char*)temp_buffer, "+MQTTSUBRECV:");
                if (cloudMsg) {
                    printf("检测到云平台下发消息: %s\n", cloudMsg);
                    
                    // 查找消息内容部分 - 定位到JSON开始
                    char *jsonStart = strchr(cloudMsg, '{');
                    if (jsonStart) {
                        // 查找JSON结束位置
                        char *jsonEnd = strrchr(jsonStart, '}');
                        if (jsonEnd) {
                            // 计算JSON长度
                            int jsonLen = jsonEnd - jsonStart + 1;
                            
                            // 使用固定大小的缓冲区
                            char jsonBuffer[MAX_JSON_LEN];
                            int copyLen = (jsonLen < MAX_JSON_LEN - 1) ? jsonLen : MAX_JSON_LEN - 1;
                            strncpy(jsonBuffer, jsonStart, copyLen);
                            jsonBuffer[copyLen] = '\0';
                            
                            printf("完整JSON: %s\n", jsonBuffer);
                            
                            // 解析content字段
                            char *contentStart = strstr(jsonBuffer, "\"content\":\"");
                            if (contentStart) {
                                contentStart += strlen("\"content\":\""); // 移动到内容开始位置
                                char *contentEnd = strchr(contentStart, '\"');
                                if (contentEnd) {
                                    // 提取content内容
                                    int contentLen = contentEnd - contentStart;
                                    
                                    // 使用固定大小的缓冲区
                                    char content[MAX_CONTENT_LEN];
                                    int contentCopyLen = (contentLen < MAX_CONTENT_LEN - 1) ? contentLen : MAX_CONTENT_LEN - 1;
                                    strncpy(content, contentStart, contentCopyLen);
                                    content[contentCopyLen] = '\0';
                                    
                                    printf("控制命令内容: %s\n", content);
                                    
                                    // 解析灯光命令
                                    char *l = strstr(content, "l:");
                                    if (l) {
                                        char LED = l[2]; // "l:0" 中的 '0'
                                        if (LED == '0' || LED == '1') {
                                            unsigned int LED_flag = LED - '0';
                                            // 使用辅助函数安全更新灯光状态
                                            update_Led_status(LED_flag);
                                            printf("云平台控制 - 灯光状态: %d\n", LED_flag);
                                        }
                                    }
                                    
                                    // 解析风扇控制命令
                                    char *f = strstr(content, "f:");
                                    if (f) {
                                        char FAN = f[2]; // "f:0" 中的 '0'
                                        if (FAN == '0' || FAN == '1') {
                                            unsigned int FAN_flag = FAN - '0';
                                            // 使用辅助函数安全更新风扇状态
                                            update_Fan_status(FAN_flag); 
                                            printf("云平台控制 - 风扇状态: %d\n", FAN_flag);
                                            
                                        }
                                    }

                                    // 解析空调控制命令
                                    char *a = strstr(content, "a:");
                                    if (a) {
                                        char COLD = a[2]; // "a:0" 中的 '0'
                                        if (COLD == '0' || COLD == '1') {
                                            unsigned int COLD_flag = COLD - '0';
                                            // 使用辅助函数安全更新空调状态
                                            update_Cold_status(COLD_flag);
                                            printf("云平台控制 - 空调状态：%d\n",COLD_flag);
                                        }
                                    }

                                    // 解析暖气控制命令
                                    char *h = strstr(content, "h:");
                                    if (h) {
                                        char HOT = h[2]; // "h:0" 中的 '0'
                                        if (HOT == '0' || HOT == '1') {
                                            unsigned int HOT_flag = HOT - '0';
                                            // 使用辅助函数安全更新暖气状态
                                            update_Hot_status(HOT_flag);
                                            printf("云平台控制 - 暖气状态：%d\n",HOT_flag);
                                        }
                                    }
                                
                                     // 解析暖气控制命令
                                    char *m = strstr(content, "m:");
                                    if (m) {
                                        char mode = m[2]; // "h:0" 中的 '0'
                                        if (mode == '0' || mode == '1') {
                                            unsigned int M_flag = mode - '0';
                                            // 使用辅助函数安全更新模式状态
                                            update_Mode_status(M_flag);
                                            printf("云平台控制 - 模式：%d\n",M_flag);
                                        }
                                    }

                                    char *x = strstr(content, "x:");
                                    if (x) {
                                        char mode = x[2]; 
                                        if (mode == '0') {
                                            Off_task();
                                            printf("一键断电成功");
                                        }
                                        else{
                                            printf("一键断电成功失败");
                                        }
                                    }

                                }
                            }
                        }
                    }
                }
                // ===== 云平台解析结束 =====
            }
        } else {
            // 无数据时不发送事件（降低CPU负载）
        }
        LOS_Msleep(100);  // 50ms轮询间隔
    }
}
//adc按键扫描任务
void key_scan_task(void)
{
    float voltage;
    int is_pressed = 0; // 0:未按下 1:按下
    int count = 0;
    int long_press_threshold = 50; // 50 * 100ms = 5秒
    
    printf("ADC按键扫描任务启动...\n");
    
    // 初始化ADC
    if (adc_dev_init() != IOT_SUCCESS) {
        printf("ADC初始化失败!\n");
        return;
    }
 
         while (1) {
        // 获取ADC电压值
        voltage = adc_get_voltage();
        
        // 检测UP键按下（电压<0.5V）
        if ((voltage < 0.5) && (is_pressed == 0)) {
            is_pressed = 1; // 标记按键已按下
            if(MODE == 0)
            {
                printf("UP键按下\n");
                // 切换LED状态
                unsigned int Led_flag = get_Led_status();
                update_Led_status(!Led_flag);
                
                printf("LED状态切换: %s\n", 
                    !Led_flag ? "开启" : "关闭");
            }
            
        } 
        // 检测DOWN键按下（电压在1.0V-1.5V之间）
        else if ((voltage > 1.0) && (voltage < 1.5) && (is_pressed == 0)&&(MODE == 0)) {
            is_pressed = 1; // 标记按键已按下
            printf("DOWN键按下\n");
          // 切换制冷状态
            unsigned int Cold_flag = get_Cold_status();
            update_Cold_status(!Cold_flag);
            
            printf("制冷状态切换: %s\n", 
                  !Cold_flag ? "开启" : "关闭");
        }
        // 检测MID键按下（电压在1.5V-2.5V之间） - 控制风扇
        else if ((voltage > 1.5) && (voltage < 2.5) && (is_pressed == 0)&&(MODE == 0)) {
            is_pressed = 1; // 标记按键已按下
            printf("MID键按下\n");
            
            // 切换风扇状态
            unsigned int Fun_flag = get_Fan_status();
            update_Fan_status(!Fun_flag);
            
            printf("风扇状态切换: %s\n", 
                  !Fun_flag ? "启动" : "关闭");
            
        }
      
         // 检测RIGHT键按下（电压在0.5V-1.0V之间） - 控制制热
        else if ((voltage > 0.5) && (voltage < 1.0) && (is_pressed == 0)&&(MODE == 0)) {
            is_pressed = 1; // 标记按键已按下
            printf("RIGHT键按下 - 制热控制\n");
            // 切换制热状态
            unsigned int Hot_flag = get_Hot_status();
            update_Hot_status(!Hot_flag);
            
            printf("制热状态切换: %s\n", 
                  !Hot_flag ? "开启" : "关闭");
            
        }
        // 按键释放检测（电压>3.2V表示无按键按下）
        else if ((voltage > 3.2) && (is_pressed == 1)) {
            is_pressed = 0; // 标记按键释放
            count = 0;      // 重置长按计数器
            printf("按键释放\n");
        } 
         // 按键持续按下（长按检测）- 仅对UP键有效
        else if ((voltage < 0.5) && (is_pressed == 1)) {
            count++;
            printf("count:%d\n",count);
            if (count >= long_press_threshold) {
                count = 0;
                printf("长按5秒以上，模式即将切换...\n");
                unsigned int MODE_flag = get_Mode_status();
                update_Mode_status(!MODE_flag);                
                printf("模式切换: %s\n", 
                !MODE_flag ?  "自动" :"手动");
                printf("MODE:%d\n",get_Mode_status());
        }
        
    }
    LOS_Msleep(100); // 100ms扫描周期
   
}
}

/***************************************************************
* 函数名称: lcd_process
* 说    明: lcd显示任务函数
* 参    数: 
  1.温度，湿度，光照
  2.风扇状态
  3.空调状态
***************************************************************/

void lcd_process(void *arg)
{  
    lcd_init();
    lcd_fill(0, 0, LCD_W, LCD_H, LCD_WHITE);
    //标题
    lcd_show_chinese(100, 0, "智慧园区", LCD_BLUE, LCD_WHITE, 32, 0);
    lcd_show_chinese(0, 34, "设备状态", LCD_BLUE, LCD_WHITE, 24, 0);
    lcd_show_chinese(150, 34, "环境数据", LCD_BLUE, LCD_WHITE, 24, 0);
    //环境数据显示
    lcd_show_chinese(150 , 66, "温度", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(202, 66, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_chinese(287, 66, "℃", LCD_BLACK, LCD_WHITE, 24, 0);

    lcd_show_chinese(150 , 98, "湿度", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(202, 98, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(294, 98, "%", LCD_BLACK, LCD_WHITE, 24, 0);

    lcd_show_chinese( 150, 130, "光照", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(202, 130, ":", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(294, 130, "lx", LCD_BLACK, LCD_WHITE, 24, 0);
    //设备数据显示
    lcd_show_chinese( 0, 66, "灯光", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(52, 66, ":", LCD_BLACK, LCD_WHITE, 24, 0);

    lcd_show_chinese( 0, 98, "空调", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(52, 98, ":", LCD_BLACK, LCD_WHITE, 24, 0);

    lcd_show_chinese( 0, 130, "暖气", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(52, 130, ":", LCD_BLACK, LCD_WHITE, 24, 0);

    lcd_show_chinese( 0, 162, "风扇", LCD_BLACK, LCD_WHITE, 24, 0);
    lcd_show_string(52, 162, ":", LCD_BLACK, LCD_WHITE, 24, 0);

    while (1)
    {   
        //环境参数显示

        lcd_show_float_num1(225, 66, tem_w, 4, LCD_BLACK, LCD_WHITE, 24);
        
        lcd_show_float_num1(225, 98, humi_s, 4, LCD_BLACK, LCD_WHITE, 24);

        lcd_show_int_num(237, 130, Light, 4, LCD_BLACK, LCD_WHITE, 24);
        
        //设备状态显示
        int LED_Status = get_Led_status();
        if(LED_Status)
        {
            lcd_show_chinese(86, 66, "开启", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(86, 66, "关闭", LCD_GREEN, LCD_WHITE, 24, 0);
        }
        
        int Cold_Status = get_Cold_status();
        if(Cold_Status)
        {
            lcd_show_chinese(86, 98, "开启", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(86, 98, "关闭", LCD_GREEN, LCD_WHITE, 24, 0);
        }

        int Hot_Status = get_Hot_status();
        if(Hot_Status)
        {
            lcd_show_chinese(86, 130, "开启", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(86, 130, "关闭", LCD_GREEN, LCD_WHITE, 24, 0);
        }

        int Fan_Status = get_Fan_status();
        if(Fan_Status)
        {
            lcd_show_chinese(86, 162, "开启", LCD_RED, LCD_WHITE, 24, 0);
        }
        else{
            lcd_show_chinese(86, 162, "关闭", LCD_GREEN, LCD_WHITE, 24, 0);
        }

        int Mode_Status = get_Mode_status();
        if(Mode_Status)
        {
            lcd_show_chinese(290, 10, "自动", LCD_BLUE, LCD_WHITE, 12, 0);
        }
        else{
            lcd_show_chinese(290, 10, "手动", LCD_BLUE, LCD_WHITE, 12, 0);
        }
        LOS_Msleep(10);

    }
}



/***************************************************************
* 函数名称: lcd_example
* 说    明: 开机自启动调用函数
* 参    数: 无
* 返 回 值: 无
***************************************************************/
void lcd_example()
{
   
    unsigned int thread_id;
    TSK_INIT_PARAM_S task = {0};
    unsigned int ret = LOS_OK;

	// 创建互斥锁（保护共享资源）
    if (LOS_MuxCreate(&g_LedMutex) != LOS_OK) {
        printf("创建LED状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_FanMutex) != LOS_OK) {
        printf("创建风扇状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_coldMutex) != LOS_OK) {
        printf("创建制冷状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_hotMutex) != LOS_OK) { // 点火状态互斥锁
        printf("创建制热状态互斥锁失败!\n");
        return;
    }
    if (LOS_MuxCreate(&g_uartMutex) != LOS_OK) {
        printf("创建串口缓冲区互斥锁失败!\n");
        return;
    }
     if (LOS_MuxCreate(&g_modeMutex) != LOS_OK) {
        printf("创建串口缓冲区互斥锁失败!\n");
        return;
    }
    Equipment_init();
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)lcd_process;
    task.uwStackSize = 4096;
    task.pcName = "lcd_tesk";
    task.usTaskPrio = 27;
    ret = LOS_TaskCreate(&thread_id, &task);
    if (ret != LOS_OK)
    {
        printf("Falied to create task ret:0x%x\n", ret);
        return;
    }
	// 创建温湿度采集任务
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)EDA_task;
    task.uwStackSize = 2048;
    task.pcName = "EDA_task";
    task.usTaskPrio = 26;  // 中优先级
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建环境采集任务失败!\n");
        return;
    }
    
    // 串口发送任务
    task.pfnTaskEntry = uart_send_task;
    task.uwStackSize = 4096;       // 需要较大栈空间处理JSON
    task.pcName = "uart_send_task";
    task.usTaskPrio = 25;          // 次高优先级
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建串口发送任务失败!\n");
        return;
    }

    // 串口接收任务
    task.pfnTaskEntry = uart_recv_task;
    task.uwStackSize = 2048;    
    task.pcName = "uart_recv_task";
    task.usTaskPrio = 24;          
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建串口接收任务失败!\n");
        return;
    }
        
      // 按键扫描任务
    task.pfnTaskEntry = (TSK_ENTRY_FUNC)key_scan_task;
    task.uwStackSize = 2048;
    task.pcName = "key_scan_task";
    task.usTaskPrio = 23;          // 最低优先级
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建按键扫描任务失败!\n");
        return;
    }
          // 自动化任务
    task.pfnTaskEntry = automatic_control_task;
    task.uwStackSize = 2048;
    task.pcName = "automatic_control_task()";
    task.usTaskPrio = 22;          // 最低优先级
    if (LOS_TaskCreate(&thread_id, &task) != LOS_OK) {
        printf("创建自动化任务失败!\n");
        return;
    }
    //感应门任务

}
APP_FEATURE_INIT(lcd_example);

